package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entiey.SpecGroup;
import com.leyou.item.entiey.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamServiceImpl specParamService;

    @Override
    public List<SpecGroupDTO> queryGroupAndParamByCategoryId(Long categoryId) {

        //1.查询规格组信息
        //1.1条件查询
        List<SpecGroup> specGroupList = this.query().eq(categoryId != null, "category_id", categoryId).list();
        //1.2转为dto对象
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(specGroupList);
/*

        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            List<SpecParamDTO> specParamDTOS = specParamService.querySpecParams(null, specGroupDTO.getId(), null);
            specGroupDTO.setParams(specParamDTOS);
        }
*/
        //2.查询规格参数
        List<SpecParamDTO> specParamDTOList = specParamService.querySpecParams(categoryId, null, null);

        //3.根据规格参数中的规格组ID字段将同一规格组的规格参数进行存放
        Map<Long, List<SpecParamDTO>> map = specParamDTOList.stream()
                .collect(Collectors.groupingBy(SpecParamDTO -> SpecParamDTO.getGroupId()));
        for (SpecGroupDTO specGroup:specGroupDTOList) {
            specGroup.setParams(map.get(specGroup.getId()));
        }
        return specGroupDTOList;
    }

    //删除规格组
    @Override
    @Transactional
    public void deleteGroupAndParam(Long id) {
        //1.删除规格参数中信息
        //1.1  查找对应category_id
        Long categoryId = this.getById(id).getCategoryId();
        //1.2 判断该规格组中是否存在规格参数
        if (categoryId != null){
            //1.3  删除参数表中的参数
            QueryWrapper<SpecParam> wrapper = new QueryWrapper<>();
            wrapper.eq("group_id",id).eq("category_id",categoryId);
            specParamService.remove(wrapper);
        }
        //2.删除规格组
        this.removeById(id);
    }
}
